package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //获取日期数组
        List<LocalDate> dateList = new ArrayList<>();
        // TODO
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //获取各个日期的营业额
        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);    //2023-10-14 00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);      //2023-10-14 23:59:59
            HashMap<String, Object> map = new HashMap<>();  //将参数封装到一个map中,传给Mapper
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);    //只有已完成的订单才能计算到营业额中
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0 : turnover;
            turnoverList.add(turnover);
        });
        //将 日期数组 和 营业额数组 封装到TurnoverReportVO对象中
        TurnoverReportVO vo = new TurnoverReportVO();
        vo.setDateList(StringUtils.join(dateList, ",")); //org.apache.commons.lang.StringUtils
        vo.setTurnoverList(StringUtils.join(turnoverList, ","));
        return vo;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        // TODO
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList=new ArrayList<>();
        List<Integer> totalUserList=new ArrayList<>();
        dateList.forEach(date->{
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String,Object> map=new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            //新增用户量
            Integer newUserAmount = userMapper.getNewUserAmountByMap(map);
            //总用户量
            Integer totalUserAmount = userMapper.getTotalUserAmountByMap(map);
            //添加到数组中
            newUserList.add(newUserAmount);
            totalUserList.add(totalUserAmount);
        });
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(dateList,","));
        userReportVO.setNewUserList(StringUtils.join(newUserList,","));
        userReportVO.setTotalUserList(StringUtils.join(totalUserList,","));
        return userReportVO;
    }

    @Override
    public SalesTop10ReportVO getTop10Sales(LocalDate begin, LocalDate end) {
        // TODO
//        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN).plusDays(1);   //当天的销量不计入排名
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getTop10Sales(beginTime,endTime);
        //使用stream流来处理,并转为List集合
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //封装到SalesTop10ReportVO,并返回
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(StringUtils.join(nameList,","));
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList,","));
        return salesTop10ReportVO;
    }

    @Override
    public OrderReportVO getCompletionRate(LocalDate begin, LocalDate end) {
        //日期列表
        ArrayList<LocalDate> dateList = new ArrayList<>();
        // TODO
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        ArrayList<Integer> totalOrderCountList = new ArrayList<>();  //总订单数列表
        ArrayList<Integer> validOrderCountList = new ArrayList<>(); //有效订单数列表
        dateList.forEach(date->{
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //当天总订单数
            HashMap<String, Object> map = new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            Integer totalOrderCount = orderMapper.selectOrderCount(map);
            totalOrderCountList.add(totalOrderCount);
            //当天有效订单数
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.selectOrderCount(map);
            validOrderCountList.add(validOrderCount);
        });

        //订单总数
        Integer totalOrderCountSum=0;
        for (Integer i : totalOrderCountList) {
            totalOrderCountSum+=i;
        }

        //有效订单数
        Integer validOrderCountSum=0;
        for (Integer i : validOrderCountList) {
            validOrderCountSum+=i;
        }

        //订单完成率
        BigDecimal orderCompletionRate = new BigDecimal((1.0*validOrderCountSum) / totalOrderCountSum);

        //封装OrderReportVO对象
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(dateList,","));
        orderReportVO.setOrderCountList(StringUtils.join(totalOrderCountList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList,","));
        orderReportVO.setTotalOrderCount(totalOrderCountSum);
        orderReportVO.setValidOrderCount(validOrderCountSum);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);

        return orderReportVO;
    }

    @Override
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            assert inputStream != null;
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
//            XSSFSheet sheet = excel.getSheet("Sheet1");
            XSSFSheet sheet = excel.getSheetAt(0);

            //起止时间
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());    //营业额
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate()); //订单完成率
            row.getCell(6).setCellValue(businessData.getNewUsers());    //新增用户数

            //获取第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount()); //有效订单
            row.getCell(4).setCellValue(businessData.getUnitPrice());   //平均客单价
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}